package org.n.shop.service.impl;

import lombok.AllArgsConstructor;
import org.n.shop.domain.dto.LoginDto;
import org.n.shop.domain.entity.User;
import org.n.shop.domain.vo.LoginVo;
import org.n.shop.mapper.UserMapper;
import org.n.shop.result.RestResult;
import org.n.shop.result.RestResultBuilder;
import org.n.shop.service.UserService;
import org.n.shop.util.MinioUtil;
import org.n.shop.util.TokenUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

import static org.n.shop.config.RedisConfig.PREFIX_USER;
import static org.n.shop.config.TokenConfig.EXPIRE_DATE;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
    private UserMapper userMapper;
    private RedisTemplate redisTemplate;
    private MinioUtil minioUtil;

    @Override
    public RestResult login(User user) {
        user = userMapper.login(user);

        String authorization = TokenUtil.token(user.getUsername(), user.getPassword());

        redisTemplate.opsForValue().set(PREFIX_USER + authorization, user.getUserId(), EXPIRE_DATE, TimeUnit.MILLISECONDS);


        if (user == null) {
            return new RestResultBuilder().fail();
        }

        return new RestResultBuilder().success(LoginVo
                .builder()
                .name(user.getName())
                .avatar(minioUtil.getObject(user.getAvatar()))
                .address(user.getLoginIp())
                .authorization(authorization)
                .build());
    }

    @Override
    public RestResult userinfo(String authorization) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        User user = userMapper.userinfo(userId);
        user.setAvatar(minioUtil.getObject(user.getAvatar()));
        return new RestResultBuilder().success(
                userMapper.userinfo(userId)
        );
    }

    @Override
    public RestResult update(String authorization, User user) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        user.setUserId(userId);

        if (userMapper.update(user) == 1) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail("更新失败");
    }

    @Override
    public RestResult uploadAvatar(String authorization, MultipartFile multipartFile) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);

        User user = userMapper.userinfo(userId);
        user.setUserId(userId);

        minioUtil.removeObject(user.getAvatar());
        user.setAvatar(minioUtil.putObject("user", multipartFile));

        if (userMapper.updateAvatar(user) == 1) {
            return new RestResultBuilder().success((Object) minioUtil.getObject(user.getAvatar()));
        }
        return new RestResultBuilder().fail("更新失败");
    }
}
